import { WeaSearchGroup, WeaFormItem, WeaUpload, WeaTools, WeaTableEdit, WeaTableEditable, WeaInput } from 'ecCom';
import { Button, Form } from 'antd';
import { toJS } from 'mobx';
import { WeaSwitch } from 'comsMobx';
import { inject, observer } from 'mobx-react';
import { WeaLocaleProvider } from 'ecCom';

const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;

@inject('addCustomerStore')
@observer
export default class Add extends React.Component {
  componentWillMount() {
    this.props.addCustomerStore.componentWillMount(this);
  }
    setCountryRef = (ref) => {
      Add.counRef = ref;
    }

    setProvRef = (ref) => {
      Add.provRef = ref;
      const alertModel = ref.alertModel.bind(ref);
      Add.provRef.alertModel = () => {
        const store = this.props.addCustomerStore;
        const { country } = store.addForm.getFormParams();
        // 绕过原来的加载城市的逻辑
        ref.props.replaceDatas = [1];
        alertModel();
        ref.props.replaceDatas = [];

        this.fetchProvs('provRef', country ? 'prov' : 'coun');
      };
    }

    setCityRef = (ref) => {
      const alertModel = ref.alertModel.bind(ref);

      Add.cityRef = ref;
      Add.cityRef.alertModel = () => {
        const store = this.props.addCustomerStore;
        const { province } = store.addForm.getFormParams();

        // 绕过原来的加载城市的逻辑
        ref.props.replaceDatas = [1];
        alertModel();
        ref.props.replaceDatas = [];

        this.fetchProvs('cityRef', province ? 'city' : 'prov');
      };
    }

    setDistrictRef = (ref) => {
      const alertModel = ref.alertModel.bind(ref);

      Add.disRef = ref;
      Add.disRef.alertModel = () => {
        const store = this.props.addCustomerStore;
        const { province, city, district } = store.addForm.getFormParams();

        // 绕过原来的加载城市的逻辑
        ref.props.replaceDatas = [1];
        alertModel();
        ref.props.replaceDatas = [];
        const callback = () => {
          if (city) {
            const { citys } = Add.disRef.state;
            const cityObj = citys.find(({ id }) => id === city);
            Add.disRef.tabsChange('district');
            cityObj && Add.disRef.cityClick(null, { ...cityObj, isParent: true });
          } else {
            const { provs } = Add.disRef.state;
            const provObj = provs.find(({ id }) => id === province);

            provObj && Add.disRef.provClick(null, provObj);
          }
        };

        if (district) return;
        if (city) return callback();

        this.fetchProvs('disRef', province ? 'city' : 'prov', callback);
      };
    }

    fetchProvs = (refName, activeKey, callback = () => {}) => {
      const store = this.props.addCustomerStore;
      const { country } = store.addForm.getFormParams();
      const obj = {
        type: 'coun',
        id: country || 1,
        isParent: true,
      };

      let url = Add[refName].state.url;
      url = `${url}${WeaTools.getFd({ ...obj })}&`;

      WeaTools.callApi(url, 'GET').then((datas) => {
        Add[refName].setState({
          counSelected: obj.id,
          provs: datas.datas,
          activeKey,
        });
        callback();
      });
    }

    resetCityBrowser() {
      Add.cityRef.setState({
        activeKey: 'prov',
        citySelected: '',
        provsSelected: '',
        citys: [],
      });
    }

    resetDistrictBrowser() {
      Add.disRef.setState({
        activeKey: 'city',
        citySelected: '',
        districtSelected: '',
        citys: [],
        districts: [],
      });
    }

    updateCountry(targetRef) {
      const country = targetRef.state.countrys.find(({ id }) => id == targetRef.state.counSelected);
      const { counRef } = Add;
      if (country && typeof (country) !== 'undefined' && (typeof (counRef) !== 'undefined')) {
        const { addForm } = this.props.addCustomerStore;
        const countryField = {
          country: {
            value: country.id,
            valueObj: [{ id: country.id, name: country.name }],
          },
        };

        addForm.updateFields(countryField);
        Add.counRef.countryClick(null, country);
        Add.counRef.tabsChange('coun');
      }
    }
    onChangeHandle = (res, obj) => {
      const store = this.props.addCustomerStore;
      const { addForm } = store;
      const { counRef, provRef, cityRef, disRef } = Add;

      let provRefIsNotUndefined = true;
      let cityRefIsNotUndefined = true;
      let disRefIsNotUndefined = true;
      if (typeof (provRef) === 'undefined') {
        provRefIsNotUndefined = false;
      }
      if (typeof (cityRef) === 'undefined') {
        cityRefIsNotUndefined = false;
      }
      if (typeof (disRef) === 'undefined') {
        disRefIsNotUndefined = false;
      }

      if (res.country) {
        const { value } = res.country;
        const empty = {
          province: { value: '', valueObj: [{}] },
          city: { value: '', valueObj: [{}] },
          district: { value: '', valueObj: [{}] },
        };
        counRef.state.countrys.forEach((p) => {
          p.selected = p.id === value;
        });
        if (value) {
          if (provRefIsNotUndefined && provRef.state.counSelected !== value && provRef.state.counSelected != '') {
            addForm.updateFields(empty);
          }
          if (cityRefIsNotUndefined && cityRef.state.counSelected !== value && cityRef.state.counSelected != '') {
            addForm.updateFields(empty);
          }
          if (disRefIsNotUndefined && disRef.state.counSelected !== value && disRef.state.counSelected != '') {
            addForm.updateFields(empty);
          }
        } else {
          addForm.updateFields(empty);
        }

        addForm.updateFields(res);
      }


      if (res.province) {
        const { value } = res.province;
        const empty = {
          city: { value: '', valueObj: [{}] },
          district: { value: '', valueObj: [{}] },
        };

        provRef.state.provs.forEach((p) => {
          p.selected = p.id === value;
        });

        if (value) {
          // const isDiff = provRef.state.provsSelected !== value
          //     &&cityRefIsNotUndefined&& cityRef.state.provsSelected !== value
          //     &&disRefIsNotUndefined&& disRef.state.provsSelected !== value;
          const provObj = { ...obj.valueObj[0], isParent: true };

          this.updateCountry(provRef);
          cityRefIsNotUndefined && cityRef.provClick(null, provObj);

          if (cityRefIsNotUndefined && cityRef.state.provsSelected !== value) {
            addForm.updateFields(empty);
          }
          if (disRefIsNotUndefined && disRef.state.provsSelected !== value) {
            addForm.updateFields(empty);
            disRef.provClick(null, provObj);
          }
        } else {
          addForm.updateFields(empty);
          this.resetCityBrowser();
          this.resetDistrictBrowser();
          cityRefIsNotUndefined && cityRef.tabsChange('prov');
          disRefIsNotUndefined && disRef.setState({
            provsSelected: '',
            activeKey: 'prov',
          });
          provRef.state.provs.forEach((p) => {
            p.selected = false;
          });
          provRef.setState({
            provsSelected: '',
          });
        }
        addForm.updateFields(res);
      }

      if (res.city) {
        const { value } = res.city;
        const empty = {
          district: { value: '', valueObj: [{}] },
        };

        cityRef.state.citys.forEach((c) => {
          c.selected = c.id === value;
        });

        if (value) {
          const { countrys, provs, counSelected, provsSelected } = cityRef.state;
          const prov = provs.find(({ id }) => id === provsSelected);
          const country = countrys.find(({ id }) => id === counSelected);
          // const isDiff = cityRef.state.citySelected !== value
          //     || (disRefIsNotUndefined && disRef.state.citySelected !== value)

          this.updateCountry(cityRef);

          if (prov) {
            provRefIsNotUndefined && provRef.provClick(null, prov);
            provRefIsNotUndefined && provRef.tabsChange('prov');
            disRefIsNotUndefined && disRef.countryClick(null, { ...country, isParent: true });
            disRefIsNotUndefined && disRef.provClick(null, { ...prov, isParent: true });
          }
          disRefIsNotUndefined && disRef.cityClick(null, { ...obj.valueObj[0], isParent: true });
          // isDiff && addForm.updateFields(empty);
          if (disRefIsNotUndefined && disRef.state.citySelected !== value) {
            addForm.updateFields(empty);
          }
        } else {
          cityRef.state.citys.forEach((c) => {
            c.selected = false;
          });
          cityRef.setState({
            citySelected: '',
          });
          this.resetDistrictBrowser();
          addForm.updateFields(empty);
        }
        addForm.updateFields(res);
      }

      if (res.district) {
        const { value } = res.district;
        let activeKey;
        if (provRefIsNotUndefined) {
          activeKey = Add.provRef.state;
        }


        disRef.state.districts.forEach((d) => {
          d.selected = d.id === value;
        });

        if (provRefIsNotUndefined) {
          if (provRef.state.provsSelected !== disRef.state.provsSelected) {
            provRef.state.provs.forEach((p) => {
              p.selected = p.id === disRef.state.provsSelected;
            });
            provRef.setState({
              provsSelected: disRef.state.provsSelected,
            });
          }
        }

        if (cityRefIsNotUndefined) {
          if (cityRef.state.citySelected !== disRef.state.citySelected) {
            cityRef.state.citys.forEach((c) => {
              c.selected = c.id === disRef.state.citySelected;
            });
            cityRef.setState({
              citySelected: disRef.state.citySelected,
            });
          }
        }

        if (value) {
          if (!activeKey) {
            provRefIsNotUndefined && provRef.tabsChange('prov');
          }
          store.setAddressInfo(value);
        } else {
          disRef.setState({
            districtSelected: '',
          });
        }
      }
    }

    render() {
      const { customerAddForm, contacterInfo, addForm, contacterTableData } = this.props.listStore;
      const { isFormInit } = addForm;
      const group = [];
      const formParams = addForm.getFormParams();
      isFormInit && toJS(customerAddForm).map((c,indexGroup) => {
        const items = [];
        let dom;
        c.items.map((fields, index) => {
          if (fields.conditionType == 'UPLOAD') {
            const key = getKey(fields);
            const bindObj = addForm.$(key);
            dom = (<div className="crm-weaupload"><WeaUpload
              ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@a1cn8i@${index}`}
              {...bindObj.bind()}
              {...fields}
              {...fields.otherParams}
              uploadId={fields.domkey[0]}
              uploadUrl="/api/crm/common/fileUpload"
              category="0,0,0"
              autoUpload
              showBatchLoad={false}
              showClearAll={false}
              multiSelection
              onChange={(ids, lists) => { addForm.updateFields({ [fields.domkey[0]]: { value: `${ids}` } }, false); }}
            /></div>);
          } else {
            const isBrowser = fields.formItemType === 'BROWSER';
            const browserType = fields.browserConditionParam ? fields.browserConditionParam.type : '';
            const isCountryBrowser = isBrowser && browserType === '258';
            const isProvBrowser = isBrowser && browserType === '2222';
            const isCityBrowser = isBrowser && browserType === '58';
            const isDisBrowser = isBrowser && browserType === '263';

            if (isCountryBrowser) {
              fields.initFunc = this.setCountryRef;
            } else if (isProvBrowser) {
              fields.initFunc = this.setProvRef;
            } else if (isCityBrowser) {
              fields.initFunc = this.setCityRef;
            } else if (isDisBrowser) {
              fields.initFunc = this.setDistrictRef;
            }

            dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@56m7om@${index}`} fieldConfig={fields} form={addForm} onChange={this.onChangeHandle.bind(this)} />;
          }
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@gbo9ft@${index}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              error={addForm.getError(fields)}
              tipPosition="bottom"
              wrapperCol={{ span: `${fields.fieldcol}` }}
            >
              {dom}
            </WeaFormItem>),
            col: 2,
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@enaoqh@${indexGroup}`} needTigger title={c.title} showGroup={c.defaultshow} items={items} />);
      });
      const enableContacter = toJS(contacterInfo.enableContacter);
      if (enableContacter) {
        const columns = toJS(contacterInfo.columns);
        const tProps = {};
        tProps.ref = 'tableObj';
        tProps.isModalEdit = false;
        tProps.columns = columns;
        tProps.datas = toJS(contacterTableData);
        tProps.title = `${getLabel(558, '提示')}:${getLabel(383072, '系统默认第一行为主联系人')}`;
        tProps.showAdd = true;
        tProps.showDelete = true;
        tProps.showCopy = true;
        // tProps.addFirstRow = true;
        tProps.onChange = this.onChange;
        tProps.onRowSelect = this.onRowSelect;
        tProps.selectedData = toJS(contacterInfo.selectedData);
        tProps.getRowSelection = this.getRowSelection;
        tProps.tableProps = { scroll: { x: columns.length * 200 } };
        const rules = {};
        columns.map((c, index) => {
          if (c.rules != '' && c.key != 'main') {
            rules[c.key] = c.rules;
          }
        });
        // console.log("rules",rules)
        tProps.validator = {
          rules,
          errorMessage: {
            // 对应规则的错误提示信息
            // required: "此项必填",
            email: `\"${getLabel(477, '电子邮件')}\"${getLabel(24944, '格式不正确')}`,
            // 可以添加自定义错误信息
          },
        };
        const items = [];
        items.push({
          com: (<WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@9o7bc5@wte`} {...tProps} />),
          col: 1,
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@kmstiu@wsg`} needTigger title={contacterInfo.title} showGroup items={items} />);
      }
      return group;
    }

    onChange=(columnDta) => {
      this.props.listStore.contacterTableData = columnDta;
    }
}
